﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;
using System.Globalization;

namespace AutoTrader
{
    public partial class AutoTraderForm
    {
        private bool OpenOrders()
        {
            string message = string.Empty;
            string BuySell = string.Empty;
            string format_string = string.Empty;
            double dBuyPrice=0, dSellPrice=0, dHiPrice=0.0, dLowPrice=0.0;
            int errNumber = 0;
            int InitialLots = 0;

            try
            {
                FailedCount = Convert.ToInt16(Settings.Settings.FailedCount);

                if (FailedCount > Convert.ToInt32(Settings.Settings.MaxDouble))
                {
                    FailedCount = 0;// 02.11.2009 P.Peev - We loss enought - restart FailedCounts.
                    myLogger.Add(string.Format("Max. Double reached - Set lots to initial quan!"));
                }

                InitialLots = Convert.ToInt16(Settings.Settings.InitialLots) * Convert.ToInt32(Math.Pow(2, FailedCount));
                if (0 != BaseOrder.ID)//if 0 there is no order - create one but first get two steps to decide buy or sell
                {
                    myLogger.Add(string.Format("Can't open New Order - OrderID not null!"));
                    return false;
                }

                if (0 != StopOrder.ID)//if 0 there is no order - create one but first get two steps to decide buy or sell
                {
                    myLogger.Add(string.Format("Can't open New Stop Order - OrderID not null!"));
                    return false;
                }

                dResultAll = obj.GetTotalResult(Settings.Settings.Instrument.Substring(4, 3), ref errNumber);
                if (errNumber < 0)
                    myLogger.Add(string.Format("Get Total Result Error.{0}", obj.GetErrDescription(errNumber)));
                else
                    myLogger.Add(string.Format("Current Result: {0} {1}", dResultAll.ToString("F3", CultureInfo.InvariantCulture), Settings.Settings.Instrument.Substring(4, 3)));

                //GetQuote

                BuyPrice2 = BuyPrice;
                SellPrice2 = SellPrice;
                Thread.Sleep(1000);
                obj.GetQuote(Settings.Settings.Instrument, ref dBuyPrice, ref dSellPrice, ref dHiPrice, ref dLowPrice, ref errNumber);

                if (errNumber < 0)
                {
                    myLogger.Add(string.Format("GetQuote fail. {0}", obj.GetErrDescription(errNumber)));
                    return false;
                }
                BuyPrice = Convert.ToDecimal(dBuyPrice);
                SellPrice = Convert.ToDecimal(dSellPrice);

                if (!StopOrderTriggered)
                {
                    if (BaseOrder.BuyOrSell == "0")
                    {
                        BuySell = "B";
                        StopOrder.Price = BuyPrice - PipsStep;
                        BaseOrder.BuyOrSell = "0";
                        StopOrder.BuyOrSell = "1";
                    }
                    else
                    {
                        BuySell = "S";
                        StopOrder.Price = SellPrice + PipsStep;
                        BaseOrder.BuyOrSell = "1";
                        StopOrder.BuyOrSell = "0";
                    }
                    /*
                                        if (BuyPrice > BuyPrice2) // growing - buy
                                        {
                                            BuySell = "B";
                                            StopOrder.Price = BuyPrice - PipsStep;
                                            BaseOrder.BuyOrSell = "0";
                                            StopOrder.BuyOrSell = "1";
                                        }
                                        else if (BuyPrice < BuyPrice2)// fall - sell 
                                        {
                                            BuySell = "S";
                                            StopOrder.Price = SellPrice + PipsStep;
                                            BaseOrder.BuyOrSell = "1";
                                            StopOrder.BuyOrSell = "0";
                                        }
                                        else
                                            continue;
                                        break;
                    */
                }
                else
                {

                    if (BaseOrder.BuyOrSell == "0")
                    {
                        BuySell = "S";
                        StopOrder.Price = SellPrice + PipsStep;
                        BaseOrder.BuyOrSell = "1";
                        StopOrder.BuyOrSell = "0";
                    }
                    else
                    {
                        BuySell = "B";
                        StopOrder.Price = BuyPrice - PipsStep;
                        BaseOrder.BuyOrSell = "0";
                        StopOrder.BuyOrSell = "1";
                    }
                }

                myLogger.Add(string.Format("Try Open New Order: Instrument:{0}, InitialLots:{1}, Action:{2}, Validity:{3}, ",
                                  Settings.Settings.Instrument, InitialLots.ToString(), BuySell, 1));

                BaseOrder.ID = obj.NewOrder(Settings.Settings.Instrument, InitialLots*1000, 0, 0, 1, BuySell, "2");
                if (BaseOrder.ID < 0)
                {
                    myLogger.Add(string.Format("New Order Error.{0}", obj.GetErrDescription(BaseOrder.ID)));
                    BaseOrder.ID = 0;
                    return false;
                }

                message = obj.GetOrdParams(BaseOrder.ID, ref errNumber);

                if (errNumber < 0)
                {
                    BaseOrder.ID = 0;
                    myLogger.Add(string.Format("New Order Error.{0}", obj.GetErrDescription(errNumber)));
                    return false;
                }

                myLogger.Add(string.Format("New Order Opened: {0} - {1}", BaseOrder.ID.ToString(), message));

                BaseOrder.Lots = InitialLots;
                BaseOrder.Price = Convert.ToDecimal(obj.GetParam("PR", message));// 

                if (BuySell == "B")
                    BuySell = "S";
                else
                    BuySell = "B";

                myLogger.Add(string.Format("Try Open Stop Order: Instrument:{0}, InitialLots:{1}, Action:{2}, Validity:{3}, ",
                                  Settings.Settings.Instrument, InitialLots.ToString(), BuySell, 1));

                StopOrder.ID = obj.NewOrder(Settings.Settings.Instrument, InitialLots*1000, (double)StopOrder.Price, 0, 3, BuySell, "2");
                if ( StopOrder.ID < 0 )
                {
                    myLogger.Add(string.Format("New Stop Order Error.{0}", obj.GetErrDescription(StopOrder.ID)));
                    obj.ClosePosition(Settings.Settings.Instrument);// cancel opened order
                    myLogger.Add(string.Format("Opened order canceled.{0}", BaseOrder.ID));
                    BaseOrder.ID = 0;
                    StopOrder.ID = 0;
                    return false;
                }

                message = obj.GetOrdParams(StopOrder.ID, ref errNumber);

                if (errNumber < 0)
                {
                    myLogger.Add(string.Format("New Stop Order Error.{0}", obj.GetErrDescription(errNumber)));
                    return false;
                }
                myLogger.Add(string.Format("NewStopOrder Opened: {0} - {1}", StopOrder.ID.ToString(), message));

                StopOrder.Lots = InitialLots;
                StopOrderTriggered = false;

                dResultAll = obj.GetTotalResult(Settings.Settings.Instrument.Substring(4, 3), ref errNumber);
                if (errNumber < 0)
                    myLogger.Add(string.Format("Get Total Result Error.{0}", obj.GetErrDescription(errNumber)));
                else
                    myLogger.Add(string.Format("Current Result: {0} {1}", dResultAll.ToString("F3", CultureInfo.InvariantCulture), Settings.Settings.Instrument.Substring(4, 3)));

                WriteOrderSettings();
            }
            catch (Exception ex)
            {
                myLogger.Add(string.Format("Runtime exception: {0}-{1}", ex.Message, ex.StackTrace));
                return false;
            }

            return true;
        }

    }
}
